#!/usr/bin/env node

/**
 * Vision Analyzer Setup Script
 * Provides easy setup and configuration for Vision Analyzer MCP Server
 */

const path = require('path');
const { spawn } = require('child_process');

// Configuration
const CONFIG = {
  name: 'Vision Analyzer',
  description: 'MCP Server for Visual Analysis',
  version: '1.2.11',
  configFile: '.env',
  configUrl: 'http://localhost:3000',
  setupMode: 'setup'
};

/**
 * Print styled header
 */
function printHeader() {
  console.log('═══════════════════════════════════════════════════════════════');
  console.log(`                 ${CONFIG.name} v${CONFIG.version}`);
  console.log(`                ${CONFIG.description}`);
  console.log('═══════════════════════════════════════════════════════════════');
  console.log();
}

/**
 * Print styled footer
 */
function printFooter() {
  console.log();
  console.log('═══════════════════════════════════════════════════════════════');
  console.log('                    Setup Complete');
  console.log('═══════════════════════════════════════════════════════════════');
}

/**
 * Start Vision Analyzer with setup mode
 */
function startSetup() {
  printHeader();

  console.log('🚀 Starting Vision Analyzer setup...');
  console.log();
  console.log('This will launch the configuration interface in your browser.');
  console.log('If the browser doesn\'t open automatically, please visit:');
  console.log(`   ${CONFIG.configUrl}`);
  console.log();
  console.log('Press Ctrl+C to stop the server at any time.');
  console.log();

  // Start Vision Analyzer with setup argument
  const args = [CONFIG.setupMode];
  const child = spawn('node', [path.join(__dirname, '../index.js'), ...args], {
    stdio: 'inherit',
    shell: process.platform === 'win32'
  });

  // Handle child process events
  child.on('error', (error) => {
    console.error('❌ Failed to start Vision Analyzer:', error.message);
    console.log();
    console.log('💡 Troubleshooting tips:');
    console.log('   1. Make sure Node.js is installed (version 16 or higher)');
    console.log('   2. Try running: node -v');
    console.log('   3. Check if all dependencies are installed: npm install');
    process.exit(1);
  });

  child.on('close', (code) => {
    if (code === 0) {
      printFooter();
      console.log('✅ Vision Analyzer setup completed successfully!');
    } else {
      console.log();
      console.log(`⚠️  Vision Analyzer exited with code ${code}`);
      console.log('   Check the logs above for any error messages.');
    }
    process.exit(code);
  });

  // Handle process signals
  process.on('SIGINT', () => {
    console.log();
    console.log('🛑 Stopping Vision Analyzer...');
    child.kill('SIGINT');
  });

  process.on('SIGTERM', () => {
    console.log();
    console.log('🛑 Stopping Vision Analyzer...');
    child.kill('SIGTERM');
  });
}

/**
 * Show configuration status
 */
function showStatus() {
  printHeader();

  console.log('📊 Checking Vision Analyzer configuration status...');
  console.log();

  // Try to load configuration checker
  try {
    const configChecker = require('../config-checker');
    const projectRoot = path.resolve(__dirname, '..');
    const configStatus = configChecker.checkEnvConfiguration(projectRoot);

    if (configStatus.isValid) {
      console.log('✅ Configuration is valid and complete');
      console.log(`   Provider: ${configStatus.currentProvider || 'Not configured'}`);
      console.log(`   API Key: ${configStatus.hasApiKey ? '✓ Configured' : '✗ Missing'}`);
      console.log();
      console.log('💡 Vision Analyzer is ready to use!');
      console.log('   You can start it with: npm start');
    } else {
      console.log('⚠️  Configuration incomplete or invalid');
      console.log(`   Status: ${configStatus.message}`);
      console.log();
      console.log('🔧 Please run the setup to configure Vision Analyzer:');
      console.log('   npm run setup');
      console.log('   or');
      console.log('   npm start -- --setup');
    }
  } catch (error) {
    console.log('❌ Unable to check configuration status:', error.message);
    console.log();
    console.log('💡 Please ensure all dependencies are installed:');
    console.log('   npm install');
  }

  printFooter();
}

/**
 * Show help information
 */
function showHelp() {
  printHeader();

  console.log('Usage:');
  console.log('  npm run setup          Start interactive setup');
  console.log('  npm start              Start Vision Analyzer');
  console.log('  npm start -- --setup    Start in setup mode');
  console.log();
  console.log('Setup Options:');
  console.log('  --status, -s           Show configuration status');
  console.log('  --help, -h            Show this help message');
  console.log();
  console.log('Configuration:');
  console.log('  • Browser-based configuration interface');
  console.log('  • Support for multiple LLM providers');
  console.log('  • Automatic port conflict resolution');
  console.log('  • First-time setup assistance');
  console.log();
  console.log('For more information, visit the project documentation.');

  printFooter();
}

/**
 * Check Node.js version
 */
function checkNodeVersion() {
  const nodeVersion = process.version;
  const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);

  if (majorVersion < 16) {
    console.error('❌ Node.js version 16 or higher is required');
    console.error(`   Current version: ${nodeVersion}`);
    console.error('   Please upgrade Node.js from https://nodejs.org/');
    process.exit(1);
  }
}

/**
 * Parse command line arguments
 */
function parseArgs() {
  const args = process.argv.slice(2);

  return {
    command: args[0] || 'setup',
    flags: args.slice(1)
  };
}

/**
 * Check if required dependencies are installed
 */
function checkDependencies() {
  const fs = require('fs');
  const path = require('path');

  const requiredPackages = ['ajv'];
  const nodeModulesPath = path.join(__dirname, '../node_modules');

  // Check if node_modules exists
  if (!fs.existsSync(nodeModulesPath)) {
    console.log('📦 Dependencies not found. Installing...');
    console.log('Please run: npm install');
    process.exit(1);
  }

  // Check for required packages
  const missingPackages = requiredPackages.filter(pkg => {
    const pkgPath = path.join(nodeModulesPath, pkg);
    return !fs.existsSync(pkgPath);
  });

  if (missingPackages.length > 0) {
    console.log(`📦 Missing dependencies: ${missingPackages.join(', ')}`);
    console.log('Please run: npm install');
    process.exit(1);
  }

  console.log('✅ All dependencies are installed');
}

/**
 * Main setup function
 */
function main() {
  // Check dependencies first
  checkDependencies();

  const { command, flags } = parseArgs();

  switch (command) {
    case 'setup':
    case 'install':
      checkNodeVersion();
      startSetup();
      break;

    case 'status':
    case 's':
    case '--status':
    case '-s':
      showStatus();
      break;

    case 'help':
    case 'h':
    case '--help':
    case '-h':
      showHelp();
      break;

    default:
      if (command.startsWith('--')) {
        // Handle flags as default command
        checkNodeVersion();
        startSetup();
      } else {
        console.log(`Unknown command: ${command}`);
        console.log();
        showHelp();
        process.exit(1);
      }
      break;
  }
}

// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
  console.error('❌ Unexpected error:', error.message);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ Unhandled promise rejection:', reason);
  process.exit(1);
});

// Run main function
if (require.main === module) {
  main();
}

module.exports = { startSetup, showStatus, showHelp };